const Entity = require('../../shared/entity/Entity')
const MenuType = require('./MenuType')
const { MENU_DEFAULT_PARENT } = require('./constants')

const arrayToTree = require('array-to-tree')
const R = require('ramda')

const toTree = R.compose((d) =>
  arrayToTree(d, {
    parentProperty: 'parentId',
    childrenProperty: 'children',
  })
)
const sort = R.sort(R.ascend(R.prop('sort')))
const sortTree = (list) => {
  const newList = sort(list)
  for (let i = 0; i < newList.length; i++) {
    if (newList[i].children && newList[i].children.length) {
      newList[i].children = sortTree(newList[i].children)
    }
  }
  return newList
}
const toMenuTree = R.compose(sortTree, toTree)

const descriptor = {
  name: { required: true, message: '菜单名称不能为空' },
  code: { required: true, message: '菜单编码不能为空' },
}
class Menu extends Entity {
  name
  code
  description
  url
  icon
  type = MenuType.MENU
  parentId = MENU_DEFAULT_PARENT
  sort = 0
  systemId
  constructor(data) {
    super(descriptor, data)
    this.init(data)
  }
  isRoot() {
    return this.parentId === MENU_DEFAULT_PARENT
  }
  static menuListToTree(menuList) {
    return toMenuTree(menuList)
  }
  static listGroupByType(menuList = []) {
    const menuTypeIs = R.curry((type) =>
      R.compose(R.equals(type), R.prop('type'))
    )
    const data = R.groupBy(
      R.cond([
        [menuTypeIs(MenuType.MENU), R.always('menuList')],
        [menuTypeIs(MenuType.BUTTON), R.always('buttonList')],
        [menuTypeIs(MenuType.OTHER), R.always('otherList')],
      ]),
      menuList
    )
    const getRes = R.applySpec({
      menuList: R.propOr([], 'menuList'),
      buttonList: R.propOr([], 'buttonList'),
      otherList: R.propOr([], 'otherList'),
    })
    const res = getRes(data)
    res.menuList = Menu.menuListToTree(res.menuList)
    return res
  }
  static create(data) {
    return new Menu(data)
  }
}

module.exports = Menu
